﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using System.Collections.Generic;

public partial class companypart_CompanySubscription : System.Web.UI.Page
{
    List<string> fields = new List<string>();
    ArrayList values = new ArrayList();
    List<string> types = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected override void InitializeCulture()
    {
        if (Session["CurrentCulture"] != null)
        {
            string lang = Session["CurrentCulture"].ToString();
            if (lang != null && lang != "")
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
                // Thread.CurrentThread.CurrentCulture.Calendar=new  System.Globalization.GregorianCalendar();

            }
        }
    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {

        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFA8'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
    protected void aore_Click(object sender, EventArgs e)
    {
        
        LinkButton lk = (LinkButton)sender;
        string[] bb =lk.ToolTip.Split(',');//[0];
         ViewState["pro_id"]=bb[0];
         ViewState["freq_id"] = bb[2];


         
         if (DateTime.Parse(bb[1]) >DateTime.Now)//lk.Text.Contains("ذ"))
        {
             //checking if there internal copies for the product and company
            //DataSet ds1 = DB.getdata("select * from ");

            save.Visible = false;
            lnkae.Visible = true;
            DataSet ds= DB.getdata("select * from company_product where id=" + bb[0]);
            DataRow dr=ds.Tables[0].Rows[0];
            paidfees.Text = dr["copyprice"].ToString();
            copyno.Text = dr["copyno"].ToString();
            DatePicker1.SelectedDateString = dr["startdate"].ToString();
            DatePicker2.SelectedDateString = dr["enddate"].ToString();
            if (dr["distributer_id"].ToString() != null)
            {
                dist.SelectedIndex = dist.Items.IndexOf(dist.Items.FindByValue(dr["distributer_id"].ToString()));
            }

        }
        else
        {
            save.Visible = true;
            lnkae.Visible = false;
            paidfees.Text = "";
            copyno.Text = "";
            DatePicker1.SelectedDateString = "";
            DatePicker2.SelectedDateString = "";
        }
        ////////////////////////////////////////////
    ScriptManager.RegisterStartupScript(this.up1, this.GetType(), "hj", "there();", true);

    }
    protected void save_Click(object sender, EventArgs e)
    {
        /////////////////// we have cases/////////////
        /////////////new sub/////////
        //////////sub edited with higher end date continue filling///////////
        /////////////sub edited with lower end date (no prob) if lower than now it is ended/////
        //////////sub edited with higher start date delete the past edition///////////
        //////////sub edited with lower start date add another past edition///////////



        fields.Clear();
        types.Clear();
        values.Clear();
        /////////////

        fields.Add("distributer_id");
        types.Add("int");
        values.Add(dist.SelectedValue);
        ///////////////////////
        fields.Add("copyno");
        types.Add("int");
        values.Add(copyno.Text);
        ///////////////////////////////
        fields.Add("copyprice");
        types.Add("int");
        values.Add(double.Parse(paidfees.Text));
        /////////////////////////////
        fields.Add("startdate");
        types.Add("datetime");
        values.Add(DatePicker1.SelectedDate);
        /////////////////////////////
        fields.Add("enddate");
        types.Add("datetime");
        values.Add(DatePicker2.SelectedDate);
        /////////////////////////////
        /////////////////////////////
        if (!string.IsNullOrEmpty(ViewState["freq_id"].ToString()))
        {
            fields.Add("freq_id");
            types.Add("int");
            values.Add(ViewState["freq_id"].ToString());
        }
        /////////////////////////////


        int ff = (int)DB.UPDATE("company_product", "int,id," + ViewState["pro_id"].ToString(), fields, types, values);

         ////////////////////////////////////////////////////////////////////////////////////////       
               //ibrahim comment
        //DateTime myfirst = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
        //string first = myfirst.ToString("yyyy-MM-dd");

        //DateTime date = myfirst.AddMonths(1).AddDays(-1);

        //string last = date.ToString("yyyy-MM-dd");
               //ibrahim comment 
               
        //ibrahim code 
        string first = DatePicker1.SelectedDate.Date.ToString("yyyy-MM-dd");
        DateTime date = DatePicker2.SelectedDate.Date;
        string last = date.ToString("yyyy-MM-dd");      
        // ibrahim code 
        ////////////////incase of enddate is lower than current date////////////////////
                //DateTime subdate = DateTime.Parse(Session["subend"].ToString());
                DateTime subdate = DB.GetSubDate(Session["company_id"].ToString());
                DateTime date2=DateTime.MinValue ;
                DataSet ds = DB.getdata("select * from daily_checking where company_product_id=" + ViewState["pro_id"].ToString() + " and issuedate between '"+first+"' and '"+last+"' ORDER BY issuedate DESC");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    date2 = DatePicker1.SelectedDate;
                }
        
                 else
                {
                    //ibrahim comment
                  //if (DateTime.Parse( ds.Tables[0].Rows[0]["issuedate"].ToString())<=DateTime.Now)
                  //  {
                  //      date2 = DateTime.Parse(ds.Tables[0].Rows[0]["issuedate"].ToString());

                  //  }
                    //ibrahim comment 
                    //ibrahim code
                    date2 = DateTime.Parse(ds.Tables[0].Rows[0]["issuedate"].ToString());
                    //ibrahim code
                }
                if (string.IsNullOrEmpty(ViewState["freq_id"].ToString()))
                {
                    DataSet ds2 = DB.getdata("Select * from daily_checking  where issuedate <= " +DatePicker2.SelectedDate.ToShortDateString() +" and issuedate >= " + DatePicker1.SelectedDate.ToShortDateString());
                    if (ds2.Tables[0].Rows.Count == 0)
                    {
                        adddate(date2.ToShortDateString());
                    }

                }
                else  if (date2 != DateTime.MinValue)
                   {
                    
                    ds = DB.getdata("select * from frequencies where id=" + ViewState["freq_id"].ToString());
                    string kk = ds.Tables[0].Rows[0]["type"].ToString();
                    int vv = int.Parse(ds.Tables[0].Rows[0]["nodays"].ToString());
                    switch (kk)
                    {
                        case "w":
                            adddate(date2.ToShortDateString());
                            date2 = date2.AddDays(vv*7);
                            if ((date2 <= date) && (date2 <= subdate))
                            {
                                
                                goto case "w";
                            }
                            else
                            {
                            break;
                            }
                        case "d":
                            
                            adddate(date2.ToShortDateString());
                            date2 = date2.AddDays(vv*1);
                            if ((date2 <= date) && (date2 <= subdate))
                            {
                               
                                goto case "d";
                            }
                            else
                            {
                                break;
                            }
                        case "m":
                            adddate(date2.ToShortDateString());
                            date2 = date2.AddMonths(vv);
                            if ((date2 <= date) && (date2 <= subdate))
                            {
                                adddate(date2.ToShortDateString());
                               
                            }
                           
                                break;
                            
                        default:
                          
                            break;

                    }
                    
                }


                   
                

            Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم التسجيل بنجاج');", true);
           // GridView1.DataBind();
            Response.Redirect("~/companypart/SubscriptionInternals.aspx?proid=" + ViewState["pro_id"].ToString());


    }


    public void adddate(string date)
    {
        ///////////////////////////////////////
        fields.Clear();
        types.Clear();
        values.Clear();
        /////////////
        fields.Add("company_product_id");
        types.Add("int");
        values.Add(ViewState["pro_id"].ToString());
        ///////////////////////
        /////////////
        fields.Add("receivedcopy");
        types.Add("int");
        values.Add(0);
        ///////////////////////
        /////////////////////////////
        fields.Add("issuedate");
        types.Add("datetime");
        values.Add(date);
        /////////////////////////////
        /////////////
        fields.Add("company_id");
        types.Add("int");
        values.Add(Session["company_id"].ToString());
        ///////////////////////
        /////////////
        fields.Add("delivered");
        types.Add("string");
        values.Add("0");
        ///////////////////////

      int  ff = (int)DB.INSERT("daily_checking", fields, types, values);

                

       
    
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            HiddenField vv = (HiddenField)e.Row.FindControl("are");
           
            LinkButton lk = (LinkButton)e.Row.FindControl("aore");
         
            DateTime ff = DateTime.Parse(lk.ToolTip.Split(',')[1]);
            if (ff > DateTime.Now)
            {
                lk.Text = this.GetLocalResourceObject("lk").ToString();
                HyperLink lkps = (HyperLink)e.Row.FindControl("edits");
                lkps.Visible = true;
                //lk.Text = "تعديل او حذف الاشتراك الحالى";
            }
            else
            {
                lk.Text = this.GetLocalResourceObject("lk2").ToString();//"~/companypart/App_LocalResources/CompanySubscription.aspx.resx", 
               // lk.Text = "لا توجد اشتراكات اضافة جديد";
            
            }
        }
    }

    protected void edit_Click(object sender, EventArgs e)
    {
        save.Visible = true;
    }
    protected void delete_Click(object sender, EventArgs e)
    {
        DB.DELETE("daily_checking", "int,company_product_id," + ViewState["pro_id"].ToString());
        /////////////////////////////////////////////////////////////////////////////////////////
        DB.DELETE("internal_checking", "int,company_product_id," + ViewState["pro_id"].ToString());
        DB.DELETE("internal_copies", "int,company_product_id," + ViewState["pro_id"].ToString());
       
        /////////////////////////////////////////////////////////////////////////////////////////
        fields.Clear();
        types.Clear();
        values.Clear();
        /////////////

        /////////////////////////////
        fields.Add("startdate");
        types.Add("datetime");
        values.Add(DateTime.Now.AddDays(-2).ToShortDateString());
        /////////////////////////////
        fields.Add("enddate");
        types.Add("datetime");
        values.Add(DateTime.Now.AddDays(-2).ToShortDateString());
        /////////////////////////////
        int ff = (int)DB.UPDATE("company_product", "int,id," + ViewState["pro_id"].ToString(), fields, types, values);



        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم الالغاء بنجاج');", true);
        GridView1.DataBind();

    }
}
